//
//  LCAccLoginViewController.m
//  wan77h5
//
//  Created by jiukuyinyue on 2017/9/1.
//  Copyright © 2017年 LC. All rights reserved.
//

#import "LCAccLoginViewController.h"
#import "LCLoginTextField.h"

#import "ViewController.h"
#import "LCHorizontalGrideView.h"
#import "JPUSHService.h"

@interface LCAccLoginViewController ()<LCHorizontalGrideViewDataSource,LCHorizontalGrideViewDelegate>


@property (weak, nonatomic) UITextField *userTextField;
@property (weak, nonatomic) UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIImageView *userImageView;
@property (weak, nonatomic) IBOutlet UIImageView *codeImageView;

@property (weak, nonatomic) IBOutlet UIButton *loginButton;
@property (weak, nonatomic) IBOutlet UIButton *findPasswordButton;

@property (strong,nonatomic) LCHorizontalGrideView  *horizontalGrideView;

@property (weak, nonatomic) IBOutlet UILabel *thirdLoginLabel;
@property (weak, nonatomic) IBOutlet UIView *thirdLoginView;
@property (strong, nonatomic) NSArray *thirdLoginArray;

@end

@implementation LCAccLoginViewController

-(void)viewWillAppear:(BOOL)animated{
    //    NSLog(@"-(void)viewWillAppear:(BOOL)animated");
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    self.rightTitle = @"注册";

    [super viewDidLoad];
    
    self.title = @"登录";
    [self.navigationController setNavigationBarHidden:NO animated:NO];
    _loginButton.enabled = NO;//禁用
    [self setupLogin];
    
    [_userTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [_passwordTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
}
-(void)rightBtnAction{
    NSLog(@"MobileRegistered");
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MobileRegistered" bundle:nil];
    UIViewController *controller = [sb instantiateInitialViewController];
    [self.navigationController pushViewController:controller animated:YES];
}

#pragma mark - 初始化布局
-(void)setupLogin{
    LCLoginTextField *userTextField = [[LCLoginTextField alloc] init];
    userTextField.font = [UIFont systemFontOfSize:15];
    userTextField.backgroundColor = [UIColor whiteColor];
    userTextField.borderStyle = UITextBorderStyleNone;
    userTextField.layer.borderColor = RGBColor(255, 255, 255).CGColor;
    userTextField.layer.borderWidth = 1;
    userTextField.layer.cornerRadius = 5;
    userTextField.keyboardType = UIKeyboardTypeNumberPad;
    userTextField.placeholder = @"手机号";

    _userTextField = userTextField;
    [self.view insertSubview:userTextField atIndex:0];
    
    LCLoginTextField *passwordTextField = [[LCLoginTextField alloc] initWithFrame:CGRectMake(54, 300, 211, 30)];
    passwordTextField.font = [UIFont systemFontOfSize:15];
    passwordTextField.backgroundColor = [UIColor whiteColor];
    passwordTextField.borderStyle = UITextBorderStyleNone;
    passwordTextField.layer.borderColor = RGBColor(255, 255, 255).CGColor;
    passwordTextField.layer.borderWidth = 1;
    passwordTextField.layer.cornerRadius = 5;
    passwordTextField.placeholder = @"请输入密码";
    passwordTextField.secureTextEntry = YES;//输入*号显示
    
    _passwordTextField = passwordTextField;
    [self.view insertSubview:passwordTextField atIndex:0];
    
    
    [_userImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(userTextField.mas_centerY);
        make.width.offset(22);
        make.left.offset(30);
    }];
    
    [userTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(104);
        make.left.equalTo(_userImageView.mas_left).offset(-8);
        make.right.offset(-30);
        
        make.height.offset(40);
    }];
    [_codeImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(userTextField.mas_bottom).offset(20);
        make.width.offset(25);
        make.left.offset(30);
    }];
    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_codeImageView.mas_left).offset(-6);
        make.right.offset(-30);
        make.centerY.equalTo(_codeImageView.mas_centerY);
        make.height.offset(40);
    }];
    
    
    [_loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(passwordTextField.mas_bottom).offset(20);
        make.left.equalTo(_passwordTextField.mas_left).offset(0);
        make.right.equalTo(_passwordTextField.mas_right).offset(0);
        
        make.height.offset(35);
    }];
    
    [_findPasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_loginButton.mas_centerX);
        make.top.equalTo(_loginButton.mas_bottom).offset(30);
    }];
    //更多登录方式 暂时隐藏掉
    _thirdLoginLabel.hidden = YES;
    [_thirdLoginLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(_findPasswordButton.mas_centerX);
        make.top.equalTo(_findPasswordButton.mas_bottom).offset(50);
    }];
    [_thirdLoginView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_thirdLoginLabel.mas_bottom).offset(30);
        make.height.offset(150);
        make.left.right.offset(0);
    }];
    
    [self setupThirdLogin];
}

- (void)setupThirdLogin {
    
    _thirdLoginArray = [[NSArray alloc] initWithObjects:@"微信",@"QQ", nil];
    
    self.horizontalGrideView = [[LCHorizontalGrideView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, _thirdLoginView.bounds.size.height)];
    [_thirdLoginView addSubview:self.horizontalGrideView];
    
    self.horizontalGrideView.dataSource = self;
    self.horizontalGrideView.delegate = self;
    
    [self.horizontalGrideView reloadData];
}

#pragma mark -  第三方登录授权  -
-(void)sendAuthRequest
{
    //构造SendAuthReq结构体
    SendAuthReq *req =[[SendAuthReq alloc ] init];
    req.scope = @"snsapi_userinfo" ;
    req.state = @"123";
    //第三方向微信终端发送一个SendAuthReq消息结构
    NSLog(@"[WXApi sendReq:req] = %d", [WXApi sendReq:req]);
    
}
/**
 监听键盘是否 输入用户名 密码
 */
-(void)textFieldDidChange :(UITextField *)theTextField{
    if (_passwordTextField.text.length <= 16 && _passwordTextField.text.length >= 6){
        _loginButton.enabled = YES;
    }else{
        _loginButton.enabled = NO;
    }
    
}

#pragma mark -  切换账户密码登录  -
- (IBAction)clickMobilePasswordView:(UIButton *)sender {
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"FindPwd" bundle:nil];
    UIViewController *controller = [sb instantiateInitialViewController];
    [self.navigationController pushViewController:controller animated:YES];
}

/**
 登陆判断
 */
#pragma mark -  登陆判断  -
- (IBAction)clickLoginButton:(UIButton *)sender {
    
    if([LSZSpecialPackaging isValidateMobile:_userTextField.text] == NO ){
        [SVProgressHUD showErrorWithStatus:@"请输入正确手机号"];
        return;
    }
    
    
    
    
    [_UserM hmacSHA256ShouQuanJiamiWithUserCode:@""];
    
    NSDictionary *input = @{@"mobile":[NSString stringWithFormat:@"%@", _userTextField.text],
                            @"password":[NSString stringWithFormat:@"%@", _passwordTextField.text]
                            };
    
    NSString *inputStr = [_UserM dictionaryToJson:input];
    
    NSString *signature = [_UserM hmac:inputStr withKey:[_UserM accesskey]];
    NSDictionary * jsonDic = @{
                               @"appkey":APPKEY,
                               @"input":inputStr,
                               @"signature":signature,
                               @"usercode":@"",
                               @"ip":@"0",
                               @"times":_UserM.times
                               };
    NSString *jsonStr = [_UserM dictionaryToJson:jsonDic];
    NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSString *jsonDicStr = [data base64EncodedStringWithOptions:0];
    
    [[NetworkTool sharedInstance] POSTWithUrlString:NEW_LOGIN_URL parameters:@{@"data":jsonDicStr} success:^(id responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:NULL];
        if ([[NSString stringWithFormat:@"%@", dict[@"status"]] isEqualToString:@"1"]) {
            [_UserM setUsercode:[NSString stringWithFormat:@"%@", dict[@"data"]]];
            [_UserM setMobileNum:self.userTextField.text];
            [LSZRequestData getsStatisticsForMessagesNotRead:^(BOOL isOK, NSString * STRING, NSDictionary * dic) {
                if (isOK == YES) {
                    [_UserM setSys_not_read:dic[@"data"][@"sys_not_read"]];
                    [_UserM setMsg_not_read:dic[@"data"][@"msg_not_read"]];
                    NSNotification *notification =[NSNotification notificationWithName:@"ANewMessage" object:nil userInfo:nil];
                    [[NSNotificationCenter defaultCenter] postNotification:notification];
                    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ANewMessage" object:nil];
                }
            }];
            //在登录的地方也需要添加
            [JPUSHService setAlias:dict[@"data"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                NSLog(@"%@",iAlias);
                if (iResCode == 0) {
                    NSLog(@"添加别名成功");
                }
            } seq:0];
            if (![dict[@"data"] isEqualToString:@""]) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    [SVProgressHUD showSuccessWithStatus:dict[@"msg"]];
                    [self.navigationController popToRootViewControllerAnimated:YES];
                    [self performSelector:@selector(loginSuccessAndloadShopData) withObject:nil/*可传任意类型参数*/ afterDelay:0.25];
                }];
                [[NSNotificationCenter defaultCenter] postNotificationName:LOGINSUCCESSFUL object:self userInfo:nil];
            }
        }else{
            [SVProgressHUD showErrorWithStatus:dict[@"msg"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"error = %@",error);
    }];
}
- (void)loginSuccessAndloadShopData {
    [LSZRequestResolutionDic initWithGetUserInformation:^(BOOL isOK, NSString * str, LSZPersonalInformationManager * manager) {
        if(isOK == YES ){
            NSUserDefaults * userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:@"yes" forKey:@"homePage"];
            NSString *uid = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
            if([uid isEqualToString:@""]){
                [self performSelector:@selector(loginSuccessAndloadShopData) withObject:nil/*可传任意类型参数*/ afterDelay:1];
            }else{
                [self loadShopData];
            }
        }
    }];
    
}

- (void)loadShopData {
    NSString *uid = [NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
    if([uid isEqualToString:@""]){
        return;
    }
#pragma mark -  加载主内商城网页  -
    NSString *url = [NSString stringWithFormat:@"%@?%@",shoopLogin,[UserPageManager getUrlStrMove]];
    NSLog(@"url = %@", url);
    Reachability *reach = [Reachability reachabilityWithHostName:url];
    if ([reach currentReachabilityStatus] == NotReachable){
        return;
    }
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:40.0f];//创建NSURLRequest
    [[PAWebView shareInstance].webView loadRequest:request];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}



#pragma mark - LCHorizontalGrideViewDataSource -
/**
 提供数据的数量
 
 @param horizontalGrideView 控件本身
 @return 返回数量
 */
- (NSInteger)numberOfItemsInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 0;
}


/**
 提供选项标题
 
 @param horizontalGrideView 当前控件
 @param index 选项下标
 @return 返回标题
 */
- (NSString *)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView titleForItemAtIndex:(NSInteger)index {
    return [NSString stringWithFormat:@"%@",_thirdLoginArray[index]];
}


/**
 提供选项的图标地址路径
 
 @param horizontalGrideView 当前控件
 @param index 选项下标
 @return 返回图标路径
 */
- (NSString *)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView iconURLForItemAtIndex:(NSInteger)index {
    if (index == 0) {
        return [NSString stringWithFormat:@"%@",@"login_iconweixin"];
    }else {
        //        if (index == 1) {
        return [NSString stringWithFormat:@"%@",@"login_iconqq"];
    }
    //    else {
    //        return [NSString stringWithFormat:@"%@",@"login_iconxlwb"];
    //    }
    
}

#pragma mark - LCHorizontalGrideViewDelegate -

- (NSInteger)numberOfRowsPerPageInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 1;//四舍五入
}

- (NSInteger)numberOfColumnsPerPageInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return 2;
}

/**
 当选项被点击回调
 
 @param horizontalGrideView 当前控件
 @param index 点击下标
 */
- (void)horizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView didSelectItemAtIndex:(NSInteger)index {
    NSLog(@"item %@ 被点击",[NSString stringWithFormat:@"%zd", index]);
}

/**
 返回当前选中的pageControl 颜色
 
 @param horizontalGrideView 当前控件
 @return 颜色
 */
- (UIColor *)colorForCurrentPageControlInHorizontalGrideView:(LCHorizontalGrideView *)horizontalGrideView {
    return [UIColor clearColor];
}


@end
